/**
* @author qleelulu
* @blog http://qleelulu.cnblogs.com
*/

var http = require('http'),
    querystring = require("querystring"),

    route = require('./route'),
    viewEngine = require('./viewEngine'),
    staticFileServer = require('./staticFileServer');

exports.runServer = function (port) {
    port = port || 8080;
    var server = http.createServer(
        function (req, res) {

            var _postData = '';

            req.on('data', function (chunk) {
                _postData += chunk;
            })
                .on('end', function () {
                    req.post = querystring.parse(_postData);
                    handlerRequest(req, res);

                });

        }).listen(port);

    console.log('Server running at http://127.0.0.1:' + port + '/');
};

/**
* 所有请求的统一入口
*/
var handlerRequest = function (req, res) {
    var actionInfo = route.getActionInfo(req);

    if (actionInfo) {
        try {
            var ct = new controllerContext(req, res);
            actionInfo.action.apply(ct, actionInfo.args);
        } catch (err) {
            handler500(req, res, err.stack);
        }
    } else {
        staticFileServer.render(req, res, handler404, handler500);
    }
};

//controller的上下文对象
var controllerContext = function (req, res) {
    this.req = req;
    this.res = res;
    this.handler404 = handler404;
    this.handler500 = handler500;
};
controllerContext.prototype.render = function (viewName, context) {
    viewEngine.render(this.req, this.res, viewName, context);
};
controllerContext.prototype.renderJson = function (json) {
    viewEngine.renderJson(this.req, this.res, json);
};
controllerContext.prototype.renderImg = function (buf) {
    viewEngine.renderImg(this.req, this.res, buf);
};

var handler404 = function (req, res) {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Page Not Found');
};

var handler500 = function (req, res, err) {
    res.writeHead(500, { 'Content-Type': 'text/plain' });
    res.end(err);
};

